﻿using System.Collections;
using System.Security.Cryptography;
using System;
using System.Text;
using UnityEngine;
using System.IO;

/// <summary>
/// 131203 hikim
/// </summary>
public class SHA
{

    public static readonly SHA Instance = new SHA();

    private readonly SHA1Managed crypto = new SHA1Managed();

    public string ComputeHashToBase64(string data)
    {
        return Convert.ToBase64String(ComputeHash(data));
    }

    public byte[] ComputeHash(string data)
    {
        if (string.IsNullOrEmpty(data))
            return null;
        byte[] bytes = Common.Encoding.GetBytes(data);
        return ComputeHash(bytes);
    }

    public string ComputeHashToBase64(byte[] data)
    {
        return Convert.ToBase64String(ComputeHash(data));
    }

    public byte[] ComputeHash(byte[] data)
    {
        return crypto.ComputeHash(data);
    }

    public string ComputeFileHashToBase64(string filePath)
    {
        string hashed = null;
        using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            hashed = ComputeHashToBase64(fs);
        }
        return hashed;
    }

    public string ComputeHashToBase64(System.IO.Stream data)
    {
        return Convert.ToBase64String(ComputeHash(data));
    }

    public byte[] ComputeHash(System.IO.Stream data)
    {
        return crypto.ComputeHash(data);
    }

    public bool Verify(string base64data, string base64hash)
    {
        if (string.IsNullOrEmpty(base64data) || string.IsNullOrEmpty(base64hash))
            return false;
        byte[] data = Convert.FromBase64String(base64data);
        byte[] hash = Convert.FromBase64String(base64hash);
        return Verify(data, hash);
    }

    public bool Verify(byte[] data, byte[] hash)
    {
        return CompareBytes(crypto.ComputeHash(data), hash);
    }

    public bool CompareBytes(byte[] a, byte[] b)
    {
        if (a.Length != b.Length)
            return false;

        for (int i = 0; i < a.Length; i++)
        {
            if (a[i] != b[i])
                return false;
        }
        return true;
    }
}
